<?

  function db_call()
  {
    global $global_db;

    include "db.php";

    if ($global_db) 
      { return; };
  
//  $db = mysql_pconnect($dbhost, $dbuser, $dbpasswd);
    $db = mysql_connect($dbhost, $dbuser, $dbpasswd);
    if (!$db) 
      { throw new Exception(mysql_error()); }

    if (!mysql_select_db("$dbname")) 
      { throw new Exception(mysql_error()); }

    mysql_query('SET NAMES "utf8"');
    $global_db = $db;
  };


  function db_exec($sql)
  {
//  echo $sql, "<br>";
    if (!mysql_query($sql))
      { throw new Exception(mysql_error()); }
  }


  function db_read_rec($sql) 
  {
    $res = mysql_query($sql);
    if (!$res) 
      { throw new Exception(mysql_error()); }

    $rec = mysql_fetch_assoc($res);
    if (!$rec) 
      { return False; }

    return $rec;
  };


  function db_read_recs($sql, $count=9999999) 
  {
    $res = mysql_query($sql);
    if (!$res) 
      { throw new Exception(mysql_error()); }

    $i = 0;
    while (($rec = mysql_fetch_assoc($res)) && ($count > 0)) 
    {
      $recs[$i++] = $rec;
      $count--;
    };

    return $recs;
  };


//-----------------------------------------------------------------------------

  function db_logon($username, $password) 
  {
    $user = db_read_rec( sprintf("SELECT * FROM users WHERE name='%s' AND password='%s'", mysql_escape_string($username), mysql_escape_string($password)) );
    if ($user) 
    {
      db_exec( sprintf("UPDATE users SET logon_date='%s' WHERE id=%d", current_time_asstr(), $user["id"]) );
    }
    return $user;
  };


  function db_read_user_by_id($id) 
  {
    return db_read_rec( sprintf("SELECT * FROM users WHERE id=%d", $id) );
  };


  function db_check_user($field, $value, $exceptid = -1) 
  {
    $SQL = sprintf("SELECT %s FROM users WHERE %s='%s'", $field, $field, mysql_escape_string($value));
    if ($exceptid <> -1)
    {
      $SQL .= sprintf(" AND id <> %d", $exceptid);
    }
    $res = mysql_query($SQL);
    if (!$res) 
      { throw new Exception(mysql_error()); }
    return mysql_num_rows($res);
  };


  function db_add_user($username, $email, $password) 
  {
    db_exec( sprintf("INSERT INTO users (name, email, password, register_date) VALUES ('%s', '%s', '%s', '%s')", 
      mysql_escape_string($username), mysql_escape_string($email), mysql_escape_string($password), current_time_asstr()) );
  };


  function db_update_user($id, $user) 
  {
    db_exec( sprintf("UPDATE users SET name='%s', email='%s', fullname='%s', comment='%s' WHERE id=%d",
      mysql_escape_string($user["name"]), mysql_escape_string($user["email"]), mysql_escape_string($user["fullname"]), mysql_escape_string($user["comment"]), $id) );
  };


  function db_change_password($id, $password)
  {
    db_exec( sprintf("UPDATE users SET password='%s' WHERE id=%d", mysql_escape_string($password), $id) );
  }


  function db_change_user_picture($id, $filename, $size)
  {
    global $msg;

    $user = db_read_user_by_id($id);

    if ($filename <> "") 
    {
//    $file = fopen($filename, 'r');
//    $image = fread($file, filesize($filename));
//    fclose($file);

      $image = file_get_contents($filename);
      if (!$image)
        { throw new Exception($msg["FileError"]); }


      if (!$user["image"]) 
      {
        db_exec( sprintf("INSERT INTO images (name, image, width, height) VALUES ('%s', '%s', %d, %d)", 
          mysql_escape_string($user["name"]), addslashes($image), $size[0], $size[1]) );
        db_exec( sprintf("UPDATE users SET image=%d WHERE id=%d", mysql_insert_id(), $id) );
      }
      else
      {
        db_exec( sprintf("UPDATE images SET name='%s', image='%s', width=%d, height=%d WHERE id=%d", 
          mysql_escape_string($user["name"]), addslashes($image), $size[0], $size[1], $user["image"]) );
      }
    }
    else
    {
      db_exec( sprintf("UPDATE users SET image=0 WHERE id=%d", $id) );
      db_exec( sprintf("DELETE FROM images WHERE id=%d", $user["image"]) );
    }
  }


  function db_delete_user($id)
  {
    //!!!Image...
    db_exec( sprintf("DELETE FROM users WHERE id=%d", $id) );
  }


  function db_update_settings($id, $user) 
  {
    db_exec( sprintf("UPDATE users SET theme='%s' WHERE id=%d",
      mysql_escape_string($user["theme"]), $id) );
  };


//-----------------------------------------------------------------------------

  function db_read_news($from, $count) 
  {
    return db_read_recs( sprintf("SELECT * FROM news ORDER BY date desc, id desc"), $count );
  };


  function db_read_news_by_id($id) 
  {
    return db_read_rec( sprintf("SELECT * FROM news WHERE id=%d", $id) );
  };


  function db_add_news($date, $text) 
  {
    db_exec( sprintf("INSERT INTO news (date, text) VALUES ('%s', '%s')", $date, mysql_escape_string($text)) );
  };


  function db_update_news($id, $date, $text) 
  {
    db_exec( sprintf("UPDATE news SET date='%s', text='%s' WHERE id=%d", $date, mysql_escape_string($text), $id) );
  };


  function db_delete_news($id)
  {
    db_exec( sprintf("DELETE FROM news WHERE id=%d", $id) );
  }


//-----------------------------------------------------------------------------

  function db_read_plugins($owner) 
  {
    return db_read_recs( sprintf("SELECT * FROM plugins WHERE owner=%d ORDER BY name", $owner ) );
  };


  function db_read_plugin_by_id($id) 
  {
    return db_read_rec( sprintf("SELECT * FROM plugins WHERE id=%d", $id ) );
  };


  function db_check_plugin($field, $value, $exceptid = 0) 
  {
    $sql = sprintf("SELECT count(*) FROM plugins WHERE %s='%s'", $field, mysql_escape_string($value));
    if ($exceptid > 0)
    {
      $sql .= sprintf(" AND id <> %d", $exceptid);
    }
    $res = db_read_rec($sql);
    return $res["count(*)"];
  };


  function db_add_plugin($owner, $plug) 
  {
    db_exec( sprintf("INSERT INTO plugins (name, description, comment, author, homepage, category, tags, create_date, update_date, owner) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
      mysql_escape_string($plug["name"]), mysql_escape_string($plug["description"]), mysql_escape_string($plug["comment"]), mysql_escape_string($plug["author"]), mysql_escape_string($plug["homepage"]), 
      mysql_escape_string($plug["category"]), mysql_escape_string($plug["tags"]), current_time_asstr(), current_time_asstr(), $owner) );
  };


  function db_update_plugin($plugid, $plug) 
  {
    db_exec( sprintf("UPDATE plugins SET name='%s', description='%s', comment='%s', author='%s', homepage='%s', category='%s', tags='%s' WHERE id=%d",
      mysql_escape_string($plug["name"]), mysql_escape_string($plug["description"]), mysql_escape_string($plug["comment"]), mysql_escape_string($plug["author"]), mysql_escape_string($plug["homepage"]), 
      mysql_escape_string($plug["category"]), mysql_escape_string($plug["tags"]), $plugid) );
  };


  function db_delete_plugin($id)
  {
    //!!!Files...
    //!!!Images...
    //!!!More...
    db_exec( sprintf("DELETE FROM plugins WHERE id=%d", $id) );
  }


//-----------------------------------------------------------------------------

  function db_read_files($plugid) 
  {
    return db_read_recs( sprintf("SELECT id, name, type, description, upload_date, download_count, length(file), plugin FROM files WHERE plugin=%d ORDER BY name", $plugid ) );
  };


  function db_read_file_by_id($fileid) 
  {
    return db_read_rec( sprintf("SELECT id, name, type, description, upload_date, download_count, length(file), plugin FROM files WHERE id=%d", $fileid ) );
  };


  function db_add_plugin_file($plugid, $info, $filename)
  {
    global $msg;

    $data = file_get_contents($filename);
    if (!$data)
      { throw new Exception($msg["FileError"]); }

    db_exec( sprintf("INSERT INTO files (name, type, description, file, upload_date, plugin) VALUES ('%s', '%s', '%s', '%s', '%s', %d)", 
      mysql_escape_string($info["name"]), mysql_escape_string($info["type"]), mysql_escape_string($info["description"]), addslashes($data), current_time_asstr(), $plugid) );

    db_exec( sprintf("UPDATE plugins SET update_date='%s' WHERE id=%d", current_time_asstr(), $plugid) );
  }


  function db_change_plugin_file($fileid, $info, $filename)
  {
    global $msg;

    if ($filename)
    {
      $data = file_get_contents($filename);
      if (!$data)
        { throw new Exception($msg["FileError"]); }

      db_exec( sprintf("UPDATE files SET name='%s', type='%s', description='%s', file='%s', upload_date='%s' WHERE id=%d",
        mysql_escape_string($info["name"]), mysql_escape_string($info["type"]), mysql_escape_string($info["description"]), addslashes($data), current_time_asstr(), $fileid) );

      $info = db_read_rec( sprintf("SELECT plugin FROM files WHERE id=%d", $fileid ) );
      db_exec( sprintf("UPDATE plugins SET update_date='%s' WHERE id=%d", current_time_asstr(), $info["plugin"]) );
    }
    else
    {
      db_exec( sprintf("UPDATE files SET description='%s' WHERE id=%d",
        mysql_escape_string($info["description"]), $fileid) );
    }
  }


  function db_register_file_download($fileid)
  {
    db_exec( sprintf("UPDATE files SET download_count=download_count + 1 WHERE id=%d", $fileid) );
  }


  function db_delete_plugin_file($fileid)
  {
    db_exec( sprintf("DELETE FROM files WHERE id=%d", $fileid) );
  }


//-----------------------------------------------------------------------------

  function db_read_images($plugid) 
  {
    return db_read_recs( sprintf("SELECT id, name, type, description, width, height, length(image), plugin FROM images WHERE plugin=%d ORDER BY description, name", $plugid ) );
  };


  function db_read_image_by_id($imageid)
  {
    return db_read_rec( sprintf("SELECT id, name, type, description, width, height, length(image), plugin FROM images WHERE id=%d", $imageid ));
  }


  function db_add_image_file($plugid, $info, $filename)
  {
    global $msg;

    $data = file_get_contents($filename);
    if (!$data)
      { throw new Exception($msg["FileError"]); }

    db_exec( sprintf("INSERT INTO images (name, type, description, width, height, image, plugin) VALUES ('%s', '%s', '%s', %d, %d, '%s', %d)", 
      mysql_escape_string($info["name"]), mysql_escape_string($info["type"]), mysql_escape_string($info["description"]), $info["width"], $info["height"], addslashes($data), $plugid) );

    db_exec( sprintf("UPDATE plugins SET update_date='%s' WHERE id=%d", current_time_asstr(), $plugid) );
  }


  function db_change_image_file($imageid, $info, $filename)
  {
    global $msg;

    if ($filename)
    {
      $data = file_get_contents($filename);
      if (!$data)
        { throw new Exception($msg["FileError"]); }

      db_exec( sprintf("UPDATE images SET name='%s', type='%s', description='%s', width=%d, height=%d, image='%s' WHERE id=%d",
        mysql_escape_string($info["name"]), mysql_escape_string($info["type"]), mysql_escape_string($info["description"]), $info["width"], $info["height"], addslashes($data), $imageid) );

      $info = db_read_rec( sprintf("SELECT plugin FROM images WHERE id=%d", $imageid ) );
      db_exec( sprintf("UPDATE plugins SET update_date='%s' WHERE id=%d", current_time_asstr(), $info["plugin"]) );
    }
    else
    {
      db_exec( sprintf("UPDATE images SET description='%s' WHERE id=%d",
        mysql_escape_string($info["description"]), $imageid) );
    }
  }


  function db_delete_image_file($imageid)
  {
    db_exec( sprintf("DELETE FROM images WHERE id=%d", $imageid) );
  }


//-----------------------------------------------------------------------------

  function db_read_updates($plugid, $from, $count) 
  {
    return db_read_recs( sprintf("SELECT * FROM updates WHERE plugin='%d' ORDER BY date desc, id desc", $plugid), $count );
  };


  function db_read_update_by_id($updid) 
  {
    return db_read_rec( sprintf("SELECT * FROM updates WHERE id=%d", $updid) );
  };


  function db_add_plugin_update($plugid, $info)
  {
    db_exec( sprintf("INSERT INTO updates (date, text, plugin) VALUES ('%s', '%s', %d)", $info["date"], mysql_escape_string($info["text"]), $plugid) );
  }


  function db_change_plugin_update($updid, $info)
  {
    db_exec( sprintf("UPDATE updates SET date='%s', text='%s' WHERE id=%d", $info["date"], mysql_escape_string($info["text"]), $updid) );
  }


  function db_delete_plugin_update($updid)
  {
    db_exec( sprintf("DELETE FROM updates WHERE id=%d", $updid) );
  }


//-----------------------------------------------------------------------------

  function db_read_comments($plugid, $from, $count) 
  {
    return db_read_recs( sprintf(
      "SELECT comments.id, comments.date, comments.user, comments.text, comments.plugin, users.name, users.fullname ".
      "FROM comments LEFT JOIN users ON comments.user = users.id WHERE comments.plugin=%d ORDER BY comments.date desc, comments.id desc", $plugid), $count );
  };


  function db_read_comment_by_id($commentid)
  {
    return db_read_rec( sprintf(
      "SELECT comments.id, comments.date, comments.user, comments.text, comments.plugin, users.name, users.fullname ".
      "FROM comments LEFT JOIN users ON comments.user = users.id WHERE comments.id=%d", $commentid));
  }


  function db_add_plugin_comment($plugid, $comment)
  {
    db_exec( sprintf("INSERT INTO comments (date, user, text, plugin) VALUES ('%s', %d, '%s', %d)", $comment["date"], $comment["user"], mysql_escape_string($comment["text"]), $plugid) );
  }


  function db_change_plugin_comment($commentid, $comment)
  {
    db_exec( sprintf("UPDATE comments SET date='%s', text='%s' WHERE id=%d", $comment["date"], mysql_escape_string($comment["text"]), $commentid) );
  }


  function db_delete_plugin_comment($commentid)
  {
    db_exec( sprintf("DELETE FROM comments WHERE id=%d", $commentid) );
  }

//-----------------------------------------------------------------------------

  function db_read_user_vote($plugid, $userid)
  {
    return db_read_rec( sprintf("SELECT * FROM votes WHERE plugin=%d and user=%d", $plugid, $userid) );
  }


  function db_add_vote($plugid, $userid, $score)
  {
    db_exec( sprintf("INSERT INTO votes (date, plugin, user, score) VALUES ('%s', %d, %d, %d)", current_time_asstr(), $plugid, $userid, $score) );
    db_exec( sprintf("UPDATE plugins SET votes_count=votes_count+1, votes_sum=votes_sum+%d, rating=votes_sum/votes_count WHERE id=%d", $score, $plugid) );
  }


  function db_delete_vote($plugid, $userid)
  {
    $vote = db_read_rec( sprintf("SELECT * FROM votes WHERE plugin=%d and user=%d", $plugid, $userid) );
    if ($vote)
    {
      db_exec( sprintf("DELETE FROM votes WHERE id=%d", $vote["id"]) );
      db_exec( sprintf("UPDATE plugins SET votes_count=votes_count-1, votes_sum=votes_sum-%d, rating=votes_sum/votes_count WHERE id=%d", $vote["score"], $plugid) );
    }
  }


//-----------------------------------------------------------------------------

  function db_read_tags($type, $lang)
  {
    $tags = db_read_recs( sprintf("SELECT * FROM tags WHERE type=%d AND (lang='%s' OR lang is NULL) ORDER BY tags.key asc", $type, $lang) );

    $res = array();
    $n = count($tags);
    for ($i = 0; $i < $n; $i++) 
    {
      $tag = $tags[$i];
      $name = $tag["name"];
      if (($tag["lang"] == $lang) || (!$res[$name]))
      {
        $res[$name] = $tag["description"];
      }
    }
    return $res;
  }


  function db_init_tags()
  {
    global $lang, $tags0, $tags1, $tags2;

    //!!!;
    $tags0 = db_read_tags(0, $lang);
    $tags1 = db_read_tags(1, $lang);
    $tags2 = db_read_tags(2, $lang);
  }


?>